<template>
  <li>
    <label>
      <input type="checkbox" v-model="todo.done" />
      <span v-show="!todo.isEdit">{{ todo.name }}</span>
    </label>
    <input
      v-show="todo.isEdit"
      type="text"
      v-model="todo.name"
      ref="iptFocus"
      @blur="handleBlur(todo, $event)"
    />
    <button class="btn btn-danger" @click="deleteTodo(todo.id)">删除</button>
    <button v-show="!todo.isEdit" class="btn btn-edit" @click="editTodo(todo)">
      编辑
    </button>
  </li>
</template>

<script>
export default {
  name: "MyItem",
  props: ["todo"],
  methods: {
    deleteTodo(id) {
      this.$bus.$emit("deleteTodo", id);
    },

    // 点击编辑时，新增todo的属性isEdit
    editTodo(todo) {
      // 已经有动态响应式的属性了
      if (todo.isEdit != undefined) {
        todo.isEdit = true;
      } else {
        // 首次添加，响应式添加
        this.$set(todo, "isEdit", true);
      }

      //   让input自动获取焦点
      this.$nextTick(function () {
        this.$refs.iptFocus.focus();
      });
    },

    // 失去焦点时就编辑成功
    handleBlur(todo, event) {
      todo.isEdit = false;
      if (event.target.value.trim() == "") {
        return alert("输入不能为空");
      }
      this.$bus.emit("editTodo", todo.id, event.target.value.trim());
    },
  },
};
</script>

<style lang="css">
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}
</style>